<template>
  <div>
    <van-row>
      <!-- 搜索 -->
    </van-row>
    <van-row>
      <!-- 左侧分类 -->
      <van-col span="6">
        <van-sticky :offset-top="46">
          <van-sidebar v-model="activeKey">
            <van-sidebar-item v-for="(item,i) in categoryList" :title="item.name"
                              @click="handleLeftMenus(item.id)"/>
          </van-sidebar>
        </van-sticky>

      </van-col>
      <!-- 右侧商品列表 -->
      <van-col span="18">
        <!-- 商品卡片列表 -->
        <van-card v-for="(item,i) in goodsList" :key="i" :price="item.price"
                  :desc="item.spec" :title="item.title" :thumb=" APIDomainName + item.pic"
                  @click="handleDetail(item.id)"/>
      </van-col>
    </van-row>
  </div>
</template>

<script>
//1.导入封装后的接口
import * as GoodsAPI from "@/api/goods.js";
import * as CategoryAPI from "@/api/category.js"

export default {
  data() {
    return {
      goodsList: [], //商品类别（指定分类id）
      categoryList: [], //分类列表
      categoryId: null,

      //左侧 导航栏
      activeKey: 0,
    }
  },

  //生命周期的钩子函数，当实例别创建好了后被调用
  created() {
    //获取所有分类
    CategoryAPI.getList().then(result => {
      console.log(result); //调式输出，也可以看看数据结构
      this.categoryList = result.data;
      this.categoryId = this.categoryList[0].id; //取分类列表中的第一个分类id
      this.getGoodsList();
    });
  },
  methods: {
    //获取当前分类id的商品列表
    getGoodsList() {
      //2.使用封装后的接口
      GoodsAPI.queryPage({
        categoryId: this.categoryId
      }).then((result) => {
        // console.log(result);
        this.goodsList = result.data.list
      });
    },

    // 单击左菜单中的某一项后，显示对应分类的商品列表
    handleLeftMenus(categoryId) {
      this.categoryId = categoryId; //更新分类id
      this.getGoodsList(); //获取该分类id对应的所有商品
    },

    handleDetail(id) {
      this.$router.push({
        name: 'goodsDetail',
        params: {id},
      });
    }
  }
}
</script>

<style lang="less" scoped="scoped">
.van-sidebar {
  width: 100px;
}

.van-sidebar-item {
  padding: 10px;
}

.van-card {
  font-size: 14px;

  .van-card__content {
    justify-content: center;

    .van-card__price {
      color: red;
      font-weight: bold;
      text-align: right;
    }
  }
}
</style>
